import java.lang.reflect.Field;

/**
 * 访问字段
 * @author zhouzhiheng98@foxmail.com 2020-10-14 10:37:13
 */
public class GetField {
    public static void main(String[] args) throws Exception  {
//        getFieldExp();
        getFieldValueExp();
    }

    public static void getFieldExp() throws Exception  {
        Class stdClass = Student.class;
        // 获取public字段"score":
        System.out.println(stdClass.getField("score"));
        // 获取继承的public字段"name":
        System.out.println(stdClass.getField("name"));
        // 获取private字段"grade":
        System.out.println(stdClass.getDeclaredField("grade"));
    }

    public static void getFieldValueExp() throws Exception {
//        Object p = new Person("Xiao Ming");
        Person p = new Person("Xiao Ming");
        System.out.println(p.getName());
        Class c = p.getClass();
        Field f = c.getDeclaredField("name");
        f.setAccessible(true);
        f.set(p,"Xiao Hong");
        Object value = f.get(p);
//        System.out.println(value);
        System.out.println(p.getName());
    }
}

class Student extends Person {
    public int score;
    private int grade;

    public Student(String name) {
        super(name);
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }
}
